package service;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/dd")
//
public class GenderCount_Servlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String jdbcUrl = "jdbc:mysql://localhost:3306/stats?serverTimezone=Asia/Shanghai";
        String dbUser = "root";
        String dbPassword = "123456";


        try {
            // 显式加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword)) {

                String query = "SELECT gender, SUM(count) as total FROM gender_stats1 GROUP BY gender";
                try (PreparedStatement stmt = conn.prepareStatement(query);
                     ResultSet rs = stmt.executeQuery()) {

                    Map<String, Integer> stats = new HashMap<>();
                    while (rs.next()) {
                        stats.put(rs.getString("gender"), rs.getInt("total"));
                    }

                    Integer maleCount = stats.getOrDefault("male", 0);
                    Integer femaleCount = stats.getOrDefault("female", 0);

                    try (PrintWriter out = resp.getWriter()) {
                        out.write(String.format("{\"male\":%d, \"female\":%d}", maleCount, femaleCount));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to fetch data from MySQL: " + e.getMessage());
        }
    }
}
